﻿using System;
using System.Collections.Generic;
using System.Reflection;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using AstUtils = Microsoft.Scripting.Ast.Utils;
using Microsoft.Scripting.Runtime;
using IronTrishul.Compiler;


namespace IronTrishul
{
    /// <summary>
    /// Language Context for WSDLDLRTest.
    /// </summary>
    public class WSDLLanguageContext : LanguageContext
    {
        /// <summary>
        /// Constructor, call parent.
        /// </summary>
        /// <param name="manager"></param>
        public WSDLLanguageContext(ScriptDomainManager manager) : base(manager)
        {
            Binder = new WSDLBinder(manager);
        }

        /// <summary>
        /// Dummy span
        /// </summary>
        private SourceSpan span = new SourceSpan(new SourceLocation(255, 255, 255), new SourceLocation(255, 255, 255));

        /// <summary>
        /// Parse a source code and return an AST, here only return the test AST.
        /// </summary>
        /// <param name="context"></param>
        /// <returns>an AST</returns>
        public override LambdaExpression ParseSourceCode(CompilerContext context)
        {
            // Create lambda expression
            LambdaBuilder program = AstUtils.Lambda(typeof(object), "WebScript1.0");

             // Add statements
            program.Body = AstUtils.Block(span, GetStatements(context , program));

            // Return result
            return program.MakeLambda();
        }

        /// <summary>
        /// Get statements.
        /// </summary>
        /// <returns>statements</returns>
        private List<Expression> GetStatements(CompilerContext context, LambdaBuilder program)
        {
            string sourceCode = context.SourceUnit.GetCode().Trim();
            StringTokenizer tok = new StringTokenizer(sourceCode);
            //tok.IgnoreWhiteSpace = false ;
            //tok.SymbolChars = new char[] { ',', ':' };
            Parser webParser = new Parser(tok);
            return webParser.GetStatements(context, program);
        }
    }
}
